<script setup>
import SqlConvert from '@/views/SqlConvert.vue'
import { defineOptions, onMounted, computed, watch } from 'vue'
import { useConfigStore } from '@/stores/config.js'
import { useMappingStore } from '@/stores/mapping.js'
import { useTemplateStore } from '@/stores/template.js'

import { useDark, usePreferredDark } from '@vueuse/core'

const configStore = useConfigStore()
const mappingStore = useMappingStore()
const templateStore = useTemplateStore()
defineOptions({
  name: 'App'
})
const initConfig = () => {
  if (window.utools) {
    // 如果是 uTools 环境且 uTools 没有存储配置信息，则保存默认配置信息
    const generatorConfig = window.utools.dbStorage.getItem('config')
    if (!generatorConfig) {
      window.utools.dbStorage.setItem('config', JSON.stringify(configStore.config))
    } else {
      configStore.refreshConfig(JSON.parse(generatorConfig))
    }
    const template = window.utools.dbStorage.getItem('template')
    if (!template) {
      window.utools.dbStorage.setItem('template', JSON.stringify(templateStore.template))
    } else {
      const tempObj = JSON.parse(template)
      Object.keys(tempObj).forEach(key => {
        templateStore.refreshTemplate(key, tempObj[key])
      })
    }
    const mapping = window.utools.dbStorage.getItem('mapping')
    if (!mapping) {
      window.utools.dbStorage.setItem('mapping', JSON.stringify(mappingStore.mapping))
    } else {
      const mappingObj = JSON.parse(mapping)
      Object.keys(mappingObj).forEach(key => {
        mappingStore.refreshMapping(key, mappingObj[key])
      })
    }
  }
  localStorage.setItem('config', JSON.stringify(configStore.config))
  localStorage.setItem('template', JSON.stringify(templateStore.template))
  localStorage.setItem('mapping', JSON.stringify(mappingStore.mapping))
}
const isSystemDark = usePreferredDark()
console.log(isSystemDark.value, 'systemDark')
// 使用 useDark 检测系统偏好主题
const isDark = useDark({
  selector: 'html', // 应用到 body 元素
  attribute: 'class', // 使用 class 来切换主题
  valueDark: 'dark', // 暗色主题的 class
  valueLight: '', // 浅色主题的 class
})
watch(isSystemDark, (newValue, oldValue) => {
  isDark.value = newValue
})
isDark.value = isSystemDark.value
// 根据 isDark 的值切换 Element Plus 的主题
const theme = computed(() => (isDark.value ? 'dark' : ''))

onMounted(() => {
  initConfig()
})
</script>
<template>
  <sql-convert/>
</template>
<style>

</style>
